package com.asset.service.impl;

import com.asset.mapper.CompanyMapper;
import com.asset.model.entity.Company;
import com.asset.model.vo.CompanyTreeNodeVO;
import com.asset.service.CompanyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CompanyServiceImpl implements CompanyService {

    @Resource
    private CompanyMapper companyMapper;

    @Override
    public List<CompanyTreeNodeVO> getCompanyTree() {
        // 1. 查询所有公司数据
        List<Company> companies = companyMapper.selectAllOrderByLevelPath();

        // 2. 转换为树形VO
        return buildCompanyTree(companies);
    }

    @Override
    public Integer selectType(int companyId) {
        return companyMapper.selectType(companyId);
    }

    /**
     * 构建公司树形结构
     */
    private List<CompanyTreeNodeVO> buildCompanyTree(List<Company> companies) {
        // 存储ID到VO的映射
        Map<Integer, CompanyTreeNodeVO> voMap = new HashMap<>();
        // 存储根节点列表
        List<CompanyTreeNodeVO> roots = new ArrayList<>();

        // 第一遍遍历：创建所有VO对象并初始化children列表
        for (Company company : companies) {
            CompanyTreeNodeVO vo = new CompanyTreeNodeVO();
            vo.setId(company.getId());
            vo.setCompanyCode(company.getCompanyCode());
            vo.setLabel(company.getName());
            vo.setParentId(company.getParentId());
            vo.setCompanyType(company.getCompanyType());
            vo.setCompanyTypeName(vo.getCompanyTypeName());
            vo.setLevelPath(company.getLevelPath());
            vo.setPurchaseLimitPrice(company.getPurchaseLimitPrice());
            vo.setBatchLimitPrice(company.getBatchLimitPrice());
            vo.setChildren(new ArrayList<>()); // 关键：初始化空children列表
            voMap.put(company.getId(), vo);
        }

        // 第二遍遍历：建立父子关系
        for (Company company : companies) {
            Integer parentId = company.getParentId();
            if (parentId != null) {
                CompanyTreeNodeVO parent = voMap.get(parentId);
                if (parent != null) {
                    // 关键：将当前节点添加到父节点的children列表中
                    parent.getChildren().add(voMap.get(company.getId()));
                }
            } else {
                // 没有父节点的就是根节点
                roots.add(voMap.get(company.getId()));
            }
        }

        return roots;
    }
}